# -*- encoding:utf-8 -*-

import os
import time

def mqtt_health(host, port, user_name, password):
    command = "mosquitto_pub -t $SYS/broker/clients/connected -h " + host + " -p " + str(port) + " -P " + password + " -u " + user_name + " -n"
    print("[INFO] " + time.strftime('%Y-%m-%d %H:%M:%S %w-%Z',time.localtime()) + " : Execute Command: " + command)
    result = os.system(command)

    if result != 0:
        print("[ERROR] %s[%d] %s[%s] mosquitto 服务状态异常" % (host, port, user_name, password))
        print("[INFO] 正在重启mosquitto服务...")
        command = "kill -9 $(ps -aux | grep /etc/mosquitto/mosquitto_mysql_" + str(port) + ".conf | awk '{print $2}')"
        print(os.system(command))
        command = "nohup /usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto_mysql_" + str(port) + ".conf >> /tmp/logs/mos_" + str(port) + ".log &"
        print(os.system(command))
        print("[INFO] mosquitto服务重启成功")

    print("[INFO] %s[%d] %s[%s] mosquitto 服务状态正常" % (host, port, user_name, password))


if __name__ == '__main__':
    list = [
        ["192.168.207.139", 1883, "11SMPSYSUSER001", "3d6bfead2eb64bd585a2ffa6fb2ab683"],
        ["192.168.207.139", 2003, "11SMPSYSUSER001", "3d6bfead2eb64bd585a2ffa6fb2ab683"],
        ["192.168.207.139", 1884, "11SMPSYSUSER001", "b328063d7ef94a298943e1992fbf88f3"],
        ["192.168.207.139", 2004, "11SMPSYSUSER001", "b328063d7ef94a298943e1992fbf88f3"],
    ]
    while True:
        for e in list:
            mqtt_health(e[0], e[1], e[2], e[3])
            time.sleep(1)
